<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="card-title">视频推荐</span>
      </div>

      <!-- 推荐类型切换 -->
      <div class="recommend-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <el-tab-pane label="个性化推荐" name="personalized">
            <el-icon><el-icon-user /></el-icon> 为你推荐
          </el-tab-pane>
          <el-tab-pane label="热门榜单" name="hot">
            <el-icon><el-icon-star-filled /></el-icon> 热门视频
          </el-tab-pane>
          <el-tab-pane label="最新发布" name="latest">
            <el-icon><el-icon-clock /></el-icon> 最新视频
          </el-tab-pane>
          <el-tab-pane label="附近视频" name="nearby">
            <el-icon><el-icon-location /></el-icon> 附近的视频
          </el-tab-pane>
          <el-tab-pane label="随机推荐" name="random">
            <el-icon><el-icon-refresh /></el-icon> 随机发现
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section" v-if="activeTab === 'hot' || activeTab === 'latest'">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="视频分类">
            <el-select v-model="queryParams.categoryId" placeholder="选择分类" clearable>
              <el-option
                v-for="category in categoryList"
                :key="category.id"
                :label="category.name"
                :value="category.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 地理位置设置 -->
      <div class="location-section" v-if="activeTab === 'nearby'">
        <el-form :inline="true" :model="locationParams" class="demo-form-inline">
          <el-form-item label="搜索半径">
            <el-select v-model="locationParams.radius" placeholder="选择范围">
              <el-option label="1公里内" :value="1"></el-option>
              <el-option label="5公里内" :value="5"></el-option>
              <el-option label="10公里内" :value="10"></el-option>
              <el-option label="20公里内" :value="20"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-location" @click="getCurrentLocation" :loading="locationLoading">
              获取当前位置
            </el-button>
            <el-button type="success" icon="el-icon-search" @click="searchNearby" :disabled="!hasLocation">
              搜索附近
            </el-button>
          </el-form-item>
        </el-form>
        <div class="location-info" v-if="hasLocation">
          <p><i class="el-icon-location-outline"></i> 当前位置：{{ currentLocation.latitude }}, {{ currentLocation.longitude }}</p>
        </div>
      </div>

      <!-- 视频列表 -->
      <div class="video-grid">
        <div v-loading="loading" class="video-container">
          <div 
            v-for="video in videoList" 
            :key="video.id" 
            class="video-card"
            @click="playVideo(video)">
            
            <div class="video-cover">
              <img :src="video.coverUrl" :alt="video.title" />
              <div class="video-duration">{{ formatDuration(video.duration) }}</div>
              <div class="video-stats">
                <span><i class="el-icon-view"></i> {{ formatCount(video.viewCount) }}</span>
                <span><i class="el-icon-star-off"></i> {{ formatCount(video.likeCount) }}</span>
              </div>
            </div>
            
            <div class="video-info">
              <h3 class="video-title">{{ video.title }}</h3>
              <p class="video-author">{{ video.nickname }}</p>
              <div class="video-meta">
                <span class="video-time">{{ parseTime(video.createdAt, '{y}-{m}-{d}') }}</span>
                <span v-if="video.location" class="video-location">
                  <i class="el-icon-location-outline"></i> {{ video.location }}
                </span>
              </div>
              <div class="video-tags" v-if="video.tags">
                <el-tag 
                  v-for="tag in video.tags.split(',')" 
                  :key="tag" 
                  size="mini" 
                  type="info">
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 没有数据时显示 -->
        <div v-if="!loading && videoList.length === 0" class="no-data">
          <el-empty description="暂无视频数据">
            <el-button type="primary" @click="refreshData">刷新数据</el-button>
          </el-empty>
        </div>
      </div>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
  </div>
</template>

<script>
import { 
  getPersonalizedRecommend, 
  getHotVideos, 
  getNearbyVideos, 
  getLatestVideos, 
  getRandomVideos 
} from "@/api/system/recommend";
import { listCategories } from "@/api/system/categories";

export default {
  name: "VideoRecommend",
  data() {
    return {
      // 加载状态
      loading: false,
      locationLoading: false,
      
      // 当前选中的Tab
      activeTab: 'personalized',
      
      // 视频列表
      videoList: [],
      total: 0,
      
      // 分类列表
      categoryList: [],
      
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        categoryId: null
      },
      
      // 地理位置参数
      locationParams: {
        radius: 5
      },
      
      // 当前位置
      currentLocation: {
        latitude: null,
        longitude: null
      },
      
      hasLocation: false
    };
  },
  
  created() {
    this.getList();
    this.getCategoryList();
  },
  
  methods: {
    /** 查询视频列表 */
    getList() {
      this.loading = true;
      
      let apiCall;
      let params = { ...this.queryParams };
      
      switch(this.activeTab) {
        case 'personalized':
          apiCall = getPersonalizedRecommend(params);
          break;
        case 'hot':
          apiCall = getHotVideos({ ...params, type: 'global' });
          break;
        case 'latest':
          apiCall = getLatestVideos(params);
          break;
        case 'nearby':
          if (!this.hasLocation) {
            this.loading = false;
            this.$message.warning('请先获取当前位置');
            return;
          }
          apiCall = getNearbyVideos({
            ...params,
            latitude: this.currentLocation.latitude,
            longitude: this.currentLocation.longitude,
            radius: this.locationParams.radius
          });
          break;
        case 'random':
          apiCall = getRandomVideos({ size: this.queryParams.pageSize });
          break;
        default:
          this.loading = false;
          return;
      }
      
      apiCall.then(response => {
        this.videoList = response.rows || response.data || [];
        this.total = response.total || this.videoList.length;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    
    /** 获取分类列表 */
    getCategoryList() {
      listCategories().then(response => {
        this.categoryList = response.rows || [];
      });
    },
    
    /** 标签页切换 */
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.resetQuery();
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 12,
        categoryId: null
      };
      this.getList();
    },
    
    /** 刷新数据 */
    refreshData() {
      this.getList();
    },
    
    /** 获取当前位置 */
    getCurrentLocation() {
      if (!navigator.geolocation) {
        this.$message.error('浏览器不支持地理定位');
        return;
      }
      
      this.locationLoading = true;
      
      navigator.geolocation.getCurrentPosition(
        (position) => {
          this.currentLocation.latitude = position.coords.latitude.toFixed(6);
          this.currentLocation.longitude = position.coords.longitude.toFixed(6);
          this.hasLocation = true;
          this.locationLoading = false;
          this.$message.success('位置获取成功');
        },
        (error) => {
          this.locationLoading = false;
          let errorMsg = '获取位置失败';
          switch(error.code) {
            case error.PERMISSION_DENIED:
              errorMsg = '用户拒绝了地理位置请求';
              break;
            case error.POSITION_UNAVAILABLE:
              errorMsg = '地理位置信息不可用';
              break;
            case error.TIMEOUT:
              errorMsg = '获取地理位置超时';
              break;
          }
          this.$message.error(errorMsg);
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 300000
        }
      );
    },
    
    /** 搜索附近视频 */
    searchNearby() {
      this.handleQuery();
    },
    
    /** 播放视频 */
    playVideo(video) {
      // 这里可以跳转到视频播放页面或者打开播放弹窗
      this.$message.info(`播放视频: ${video.title}`);
      // 示例：跳转到视频详情页
      // this.$router.push(`/video/${video.id}`);
    },
    
    /** 格式化时长 */
    formatDuration(seconds) {
      if (!seconds) return '00:00';
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    
    /** 格式化数量 */
    formatCount(count) {
      if (!count) return 0;
      if (count < 1000) return count;
      if (count < 10000) return (count / 1000).toFixed(1) + 'K';
      return (count / 10000).toFixed(1) + 'W';
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  min-height: 600px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.recommend-tabs {
  margin-bottom: 20px;
}

.filter-section, .location-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.location-info {
  margin-top: 10px;
  color: #606266;
  font-size: 14px;
}

.video-grid {
  min-height: 400px;
}

.video-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.video-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.video-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.video-cover {
  position: relative;
  width: 100%;
  height: 160px;
  overflow: hidden;
}

.video-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.video-stats {
  position: absolute;
  top: 8px;
  left: 8px;
  display: flex;
  gap: 8px;
}

.video-stats span {
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.video-info {
  padding: 12px;
}

.video-title {
  font-size: 14px;
  font-weight: bold;
  margin: 0 0 8px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.video-author {
  color: #606266;
  font-size: 13px;
  margin: 0 0 8px 0;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.video-location {
  display: flex;
  align-items: center;
  gap: 2px;
}

.video-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}
</style>
